package cn.yoshii.ad.adserver.base

import cn.yoshii.libs.jsonutil.parametricType
import cn.yoshii.libs.jsonutil.parseObject
import cn.yoshii.libs.webstarter.util.Log
import com.fasterxml.jackson.databind.JavaType
import okhttp3.Response

/**
 * date : 2021-08-22 10:07
 * author : Xiang
 * description ： 基础请求与响应数据解析
 */
object RequestUtil {

    private const val TAG = "RequestUtil"

    /**
     * 获取简单数据类型的结果
     * 这个需要放在线程中处理，因为 response?.body 可能是流数据
     */
    fun <T> formatResponse(response: Response?, dataClazz: Class<*>): NetResult<T>? {
        val type = parametricType(NetResult::class.java, dataClazz)
        return formatResponse(response) { type }
    }

    /**
     * 获取泛型数据类型结果
     * 这个需要放在线程中处理，因为 response?.body 可能是流数据
     */
    fun <T> formatResponse(response: Response?, dataType: JavaType): NetResult<T>? {
        val type = parametricType(NetResult::class.java, dataType)
        return formatResponse(response) { type }
    }

    private fun <T> formatResponse(response: Response?, resultType: () -> JavaType): NetResult<T>? {
        val content = response?.body?.string() ?: return null
        Log.i(TAG, "content: $content")
        (content.parseObject(resultType()) as NetResult<T>?)?.let {
            if (it.code != 0) {
                Log.e(TAG, "code: ${it.code}  message: ${it.message}")
            }
            return it
        }
        Log.e(TAG, "formatResponse error")
        return null
    }

}